package com.example.demo.controller;

import com.example.demo.pojo.Good;
import com.example.demo.service.GoodService;
import com.example.demo.vo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.UUID;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @Description:
 * @Param:
 * @Author:
 * @Date:
 */
@RestController
public class GoodController {

    @Autowired
    private GoodService goodService;

    //  public static final String BASE_PATH = "D:\\Program Files (x86)\\workspace-spring-tool-suite-4-4.6.2.RELEASE\\csi\\src\\main\\resources\\static\\img\\";
    public static final String BASE_PATH = "D:/Projects/IDEA/DIY/src/main/resources/static/img/";

    public static final String RETURN_URL = "http://localhost:8080/static/img/";
    /**
     * 查询全部商品
     * @return
     */
    @GetMapping("/findGoods")
    public RespBean findGoods(){
        List<Good> goodList = goodService.findGoods();
        return RespBean.success("200", "查询成功", goodList);
    }

    /**
     * 删除商品
     * @return
     */
    @PostMapping("/delGood")
    public RespBean delGood(@RequestBody Good good){
        goodService.delGood(good);
        return RespBean.success("200", "删除成功", null);
    }

    /**
     * 上传衣服图片
     */
    @PostMapping("/upLoadImg")
    public RespBean upLoadImg(MultipartFile img){
        String imageName = img.getOriginalFilename();
        String newCompanyImagePath = "";
        if (!img.isEmpty()) {
            try {

                newCompanyImagePath = BASE_PATH
                        + imageName;/**找到目标文件*/

                File newFile = new File(newCompanyImagePath);
                if (!newFile.exists()) {
                    newFile.createNewFile();
                }
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));  /**搭建通道*/
                out.write(img.getBytes());  /**将字节输入写入到BufferedOutputStream内部维护的字节数组中*/
                out.flush();  /**将内存中数据刷入硬盘文件中*/
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return RespBean.error("500", "上传失败", null);
            } catch (IOException e) {
                e.printStackTrace();
                return RespBean.error("500", "上传失败", null);
            }
        }
        String imagePath = RETURN_URL + imageName;
        Good good = new Good();

        good.setImg(imagePath);
        return RespBean.success("200", "上传成功", good);
    }




    @PostMapping("/insertGood")
    public RespBean insertGood(@RequestBody Good good){
        good.setStatus("0");
        goodService.insertGood(good);
        return RespBean.success("200", "加入成功",  null);
    }
}
